#include "sdlScreen.h" 

int SDL_Screen::init  ( Uint32 _flags, int _w, int _h, int _bpp, Uint32 _vmFlags      )  {
   pDebug( this << " int SDL_Screen::init (" << "Uint32 _flags=" << &_flags << "int _w=" << &_w << "int _h=" << &_h << "int _bpp=" << &_bpp << "Uint32 _vmFlags =" << &_vmFlags       << ")")
    int ret =  SDL_Init ( _flags );
   if ( ret != -1 ) {
      screen = SDL_SetVideoMode( _w, _h, _bpp, _vmFlags );
      if (screen == NULL ) ret = -1;
   }
   return ret;

}

void SDL_Screen::done  (  )  {
   pDebug( this << " void SDL_Screen::done ("   << ")")
    SDL_Quit();
}

int SDL_Screen::blitSurface  ( Drawable* drawable  )  {
   pDebug( this << " int SDL_Screen::blitSurface (" << "Drawable* drawable =" << &drawable   << ")")
    SDL_Surface* surface = (SDL_Surface*) drawable->getSprite()->getSurface();
   SDL_Rect destRect;
   SDL_Rect srcRect;

   Rect* posRect = drawable->getPosRect();

   destRect.x = posRect->x;
   destRect.y = posRect->y;

   Rect* geoRect = drawable->getGeometryRect();

   if ( geoRect != NULL ) {
      srcRect.x = geoRect->x;
      srcRect.y = geoRect->y;
      srcRect.w = geoRect->w;
      srcRect.h = geoRect->h;

      return SDL_BlitSurface ( surface, &srcRect, screen, &destRect);
   } 
   else return SDL_BlitSurface ( surface, NULL, screen, &destRect);

}

int SDL_Screen::flush  (  )  {
   pDebug( this << " int SDL_Screen::flush ("   << ")")
    return SDL_Flip ( screen );
}

void putPixel(SDL_Surface *surface, Uint32 x, Uint32 y,Uint8 r, Uint8 g, Uint8 b, Uint8 a ) {
   Uint32 pos = y * surface->w + x;
   Uint32 color;
   char* p = (char*) surface->pixels;
   p += (y * surface->pitch );
   p += ( x * surface->format->BytesPerPixel ) ;
   color = SDL_MapRGB( surface->format, r,g,b );
   memcpy ( p , &color , surface->format->BytesPerPixel ) ;
}

void putLine ( SDL_Surface* surface, Rect const & rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a  ) {
   float slope;
   UINT i;
   slope = (float)rect.h/(float)rect.w;

   for(i=0;i<rect.w;i++) {
      //putPixel( surface, rect.x+i, nearbyint( (float)rect.y+slope*(float)i ), r,g,b,a); 
      putPixel( surface, rect.x+i, rect.y+ (int)roundf( slope*(float)i)  , r,g,b,a); 
   }
}
